<template>
    <div class="content">
        <div class="titleSearch">
            <div class="search">
                <i class="el-icon-search"></i>
                搜索云盘内文件
            </div>
        </div>
        <div class="title">{{ title }}</div>
        <div class="fileBox" ref="fileboxRef">
            <div class="edit">
                <div class="left">
                    <input type="checkbox">
                    <span class="total">共{{ curFileList.length }}项</span>
                </div>
                <div class="right">
                    <div class="sort">
                        <i class="el-icon-sort"></i>
                        <el-dropdown trigger="click" @command="handleCommand">
                            <span class="el-dropdown-link">
                                <span>{{ tip }}</span><i class="el-icon-arrow-down el-icon--right"></i>
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="创建时间">创建时间</el-dropdown-item>
                                <el-dropdown-item command="修改时间">修改时间</el-dropdown-item>
                                <el-dropdown-item command="创建时间">创建时间</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div>
                    <div class="change" @click="handleType">
                        <i class="el-icon-s-operation"></i>
                    </div>
                </div>
            </div>
            <div class="fileWrapper" v-if="showType == '0'">
                <div class="fileItem" v-for="(item, index) in fileList" :key="index">
                    <div class="neir">
                        <div class="imgBox">
                            <img v-if="item.isFolder" src="@/assets/img/wjj.png" alt="">
                        </div>
                        <div class="name">{{ item.fileName }}</div>
                        <div class="date">{{ item.createTime }}</div>
                    </div>
                </div>
            </div>
            <div class="tableWrapper" v-else-if="showType == '1'">
                <el-table :data="tableData" style="width: 100%">
                    <el-table-column prop="fileName" label="名称">
                        <template #default="{ row }">
                            <div class="tableName">
                                <img v-if="item.isFolder" src="../../../assets/img/tableWjj.png" alt="">
                                <div class="name">{{ row.fileName }}</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column width="400px" prop="createTime" label="创建时间">
                    </el-table-column>
                    <el-table-column width="200px" prop="size" label="大小" align="left">
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div v-if="visible" class="context-menu" :style="{ top: `${y}px`, left: `${x}px` }" @click="hideMenu">
            <el-card>
                <div class="menuBox">
                    <div class="menuItem addWjj" @click="handleMenuClick('0')">新建文件夹</div>
                    <div class="menuItem addWjj" @click="handleMenuClick('1')">上传文件</div>
                    <div class="menuItem addWjj" @click="handleMenuClick('2')">上传文件夹</div>
                    <div class="menuItem addWjj" @click="handleMenuClick('3')">刷新页面</div>
                </div>
            </el-card>
        </div>
        <input type="file" ref="fileInput" class="hidden-input" @change="handleFileChange" />
        <el-dialog class="addWjjDialog" :visible.sync="dialogVisible" title="新建文件夹" width="400px">
            <div class="imgBox">
                <img src="../../../assets/img/wjj.png" alt="">

            </div>
            <el-form>
                <el-form-item>
                    <el-input v-model="folderName" placeholder="请输入文件夹名称"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button class="cancel" @click="dialogVisible = false">取消</el-button>
                    <el-button class="confirm" type="primary" @click="confirmCreate">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog class="addTypeDialog" :visible.sync="typeDialog" title="新建类型" width="400px">

            <el-form>
                <el-form-item>
                    <el-input v-model="typeName" placeholder="请输入类型名称"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button class="cancel" @click="handleTypeCancel">取消</el-button>
                    <el-button class="confirm" type="primary" @click="confirmDialogCreate">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { addType, updateType, getSliceSize, mergeFileSlice, getFileList, createFolder, checkFileExist, uploadFile, getFileByHash, uploadFileSlice } from "@/api/file"
import SparkMD5 from 'spark-md5'
import IconFont from "@/components/Icon.vue";
export default {
    components: { IconFont },
    data() {
        return {
            CHUNK_SIZE: "",
            curTypeItem: {
                "id": "1896112024899928066",
                "typeName": "文档",
                "canDelete": true,
                "creatorId": "1896109257548492802",
                "createTime": "2025-03-02T16:15:09",
                "updateTime": "2025-03-02T16:16:44",
                "deleted": "0"
            },
            typeDialog: false,
            typeName: '',
            tableData: [],
            showType: '0',
            folderName: '',
            dialogVisible: false,
            visible: false,
            x: 0,
            y: 0,
            title: '',
            tip: '按创建时间排序',
            asideList: [
                {
                    label: '全部文件',
                },
                {
                    label: '相册'
                },
                {
                    label: '我的分享'
                }
            ],
            activeIndex: 0,
            curFileList: [
                {
                    name: '1.png',
                    time: '2021-07-15 16:30',
                },
            ],
            fileList: [

            ]
        };
    },
    created() {
        this.title = this.asideList[this.activeIndex].label;
        this.getSliceSize()
        //获取文件列表
        this.getFileList()
    },

    mounted() {
        this.$refs.fileboxRef.addEventListener("contextmenu", this.showMenu);

    },

    methods: {
        async getFileList() {
            let data = {
                folderTypeId: this.curTypeItem.id,
                parentId: '',
            }
            const res = await getFileList(data)
            console.log(res, 'res2');
            this.fileList = res.data.map(item => {
                return {
                    ...item,
                    createTime: item.createTime.replace('T', ' ')
                }
            })
            this.tableData = this.fileList

        },
        async getSliceSize() {
            const res = await getSliceSize()
            console.log(res, 'ress');
            // this.CHUNK_SIZE = res.data * 1
            this.CHUNK_SIZE = '5242880'

        },
        handleTypeCancel() {
            this.curTypeItem = {}
            this.typeName = ''
            this.typeDialog = false

        },
        async confirmDialogCreate() {
            let data = {
                typeName: this.typeName
            }
            if (this.curTypeItem.id) {
                data.id = this.curTypeItem.id
                const res = await updateType(data)
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('更新成功!')
                } else {
                    this.$message.error('更新失败!')
                }
                this.typeDialog = false
                this.typeName = ''
                this.curTypeItem = {}
                this.$parent.getTypeList()

                return
            }
            const res = await addType(data)
            if (res.code == 200) {
                this.$message.success('创建成功!')
            } else {
                this.$message.error('创建失败!')
            }
            this.typeDialog = false
            this.typeName = ''
            this.$parent.getTypeList()
        },
        handleAddType() {
            this.typeDialog = true
        },
        handleType() {
            if (this.showType == '0') {
                this.showType = '1'
            } else {
                this.showType = '0'
            }
        },
        handleCommand(v) {
            console.log(v, 'v');
            this.tip = v;
        },
        async confirmCreate() {
            let data = {}
            if (this.curTypeItem.typeName == '全部文件') {

            } else {
                // fileName
                // isFolder
                // parentId
                // folderTypeId
                data.fileName = this.folderName
                data.isFolder = true
                data.parentId = ''
                data.folderTypeId = this.curTypeItem.id
            }
            const res = await createFolder(data)
            console.log(res, '900');
            if (res.code == 200) {
                this.$message.success('创建成功!')
            } else {
                this.$message.error('创建失败!')
            }
            this.dialogVisible = false
            this.folderName = ''
            this.getFileList()

        },
        handleMenuClick(flag) {
            if (flag == '0') {
                this.dialogVisible = true;
            } else if (flag == '1') {
                this.$refs.fileInput.click();

            } else if (flag == '2') {
                this.$refs.fileInput.click();

            }
        },
        showMenu(event) {
            event.preventDefault();
            this.x = event.clientX;
            this.y = event.clientY;
            this.visible = true;
            document.addEventListener("click", this.hideMenu);
        },
        hideMenu() {
            this.visible = false;
            document.removeEventListener("click", this.hideMenu);
        },
        handleAction(action) {
            console.log("选中操作:", action);
            this.hideMenu();
        },
        handleItem(item, index) {
            this.activeIndex = index;
        },
        async handleFileChange(event) {
            const file = event.target.files[0];
            if (file) {
                this.selectedFile = file;
                console.log("上传的文件:", file);
                const createChunks = (file) => {
                    const chunks = []
                    // chunks.push(file)
                    for (let i = 0; i < file.size; i += this.CHUNK_SIZE) {
                        chunks.push(file.slice(i, i + this.CHUNK_SIZE))
                    }
                    return chunks
                }
                const chunks = createChunks(file)
                console.log(chunks, 'chunks');
                const cutFile = () => {
                    return new Promise((resolve, reject) => {

                        let targets = []
                        chunks.forEach((item, index) => {
                            if (index == 0 || index == chunks.length - 1) {
                                targets.push(item)
                            } else {
                                // 首两个字节
                                targets.push(item.slice(0, 2))
                                // 中两个字节
                                targets.push(item.slice(this.CHUNK_SIZE / 2, this.CHUNK_SIZE / 2 + 2))
                                // 末两个字节
                                targets.push(item.slice(this.CHUNK_SIZE - 2, this.CHUNK_SIZE))
                            }
                        })
                        console.log(targets, '分片');
                        const spark = new SparkMD5.ArrayBuffer()
                        const fileReader = new FileReader()

                        // 把新分片的数据转换为blob对象
                        const blobs = new Blob(targets)
                        console.log(blobs, 'blobs');

                        fileReader.readAsArrayBuffer(blobs)
                        fileReader.onload = (e) => {
                            console.log(e, 'e');

                            spark.append(e.target.result)
                            // console.log(spark.end(), 'hash值')
                            // // 返回拿到的hash值
                            // console.log(spark.end(), 'hash1值');
                            resolve(spark.end())
                            // postMessage(spark.end())
                        }
                    })
                }



                const fileHash = await cutFile(file, chunks)

                const mRes = await checkFileExist({
                    fileMd5: fileHash
                })
                if (mRes.data) {
                    let data = {
                        fileMd5: fileHash,
                    }
                    const resFile = await getFileByHash(data)
                    console.log(resFile, 'zzzzzzzzzzz');
                    if (resFile.code == 200) {
                        let info = {
                            fileName: resFile.data.fileName,
                            isFolder: false,
                            parentId: '',
                            folderTypeId: this.curTypeItem.id
                        }

                        const res = await createFolder(info)
                        console.log(res,'00000000000');
                        if(res.code == 200){
                            this.$message.success('上传成功!')
                        }
                        this.getFileList()
                    }
                    return
                }
                console.log(mRes, 'mRes', fileHash);
                return
                console.log(fileHash, 'fileHash');

                console.log(chunks.size, '分片1234567890');
                console.log(chunks, 'chunks');
                const formDatas = chunks.map((chunk, index) => {
                    const formData = new FormData()
                    formData.append('file', chunk)
                    formData.append('fileMd5', fileHash)
                    formData.append('chunkIndex', index)
                    formData.append('totalChunks', chunks.length)
                    return formData
                })
                console.log(formDatas, 'formDatas');
                const pAll = []
                formDatas.forEach(async (item) => {
                    pAll.push(uploadFileSlice(item))
                })

                const res = await Promise.all(pAll)
                console.log(res, 'ssssssssx');

                let data = {
                    fileMd5: fileHash,
                    fileName: file.name
                }
                const res1 = await mergeFileSlice(data)
                console.log(res1, 'ooooooooo');


                // 上传到文件夹
                let fileInfo = {
                    fileName: res1.data.fileName,
                    folderTypeId: this.curTypeItem.id,
                    parentId: '',
                    sysFileId: res1.data.id
                }
                const res2 = await createFolder(fileInfo)

                console.log(res2, '111sss');
                this.getFileList()

                this.$refs.fileInput.value = null;
                // const fromData = new FormData();
                // fromData.append('file', file)
                // const res = await uploadFile(fromData)
                // console.log('res', res);

            }
        }
    },
};
</script>

<style lang="less" scoped>
.content {
    display: flex;
    flex-direction: column;
    flex: 1;
    padding: 20px 40px 20px 40px;

    .tableName {
        display: flex;
        align-items: center;

        img {
            width: 28px;
            height: 28px;
            margin-right: 10px;
        }
    }

    .context-menu {
        position: absolute;

        .menuBox {
            .menuItem {
                width: 200px;
                height: 30px;
                display: flex;
                align-items: center;
                border-radius: 5px;

                &:hover {
                    background-color: #f5f5f6;
                    cursor: pointer;
                }
            }
        }
    }

    .titleSearch {
        height: 54px;
        display: flex;
        // justify-content: center;
        align-items: center;

        .search {
            width: 280px;
            height: 40px;
            border-radius: 8px;
            background-color: #f6f6f7;
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #25262b5c;
            cursor: pointer;

            i {
                margin: 0 8px 0 8px;

                &::before {
                    font-size: 15px;
                }
            }
        }
    }

    .title {
        -webkit-app-region: no-drag;
        color: #333;
        font-size: 18px;
        line-height: 1.4;
        font-weight: 600;
        max-width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        height: 30px;
        margin: 20px 0;
    }

    .fileBox {
        flex: 1;
        display: flex;
        flex-direction: column;

        .edit {
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;

            .left {
                display: flex;
                align-items: center;

                .total {
                    margin-left: 10px;
                    font-size: 12px;
                    color: #25262BB8;
                }
            }

            .right {
                display: flex;
                align-items: center;

                .sort {
                    height: 28px;
                    cursor: pointer;
                    border-radius: 3px;
                    display: flex;
                    align-items: center;
                    padding: 0 8px;

                    &:hover {
                        background-color: #f5f5f6;
                    }

                    i {
                        margin-right: 5px;
                    }

                    font-size: 12px;
                    color: #25262BB8;

                    span {
                        // color: #25262B;

                    }
                }

                .change {
                    cursor: pointer;
                    border-radius: 3px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding: 0 8px;
                    width: 28px;
                    height: 28px;
                    font-size: 14px;
                    color: #25262BB8;

                    &:hover {
                        background-color: #f5f5f6;
                    }
                }
            }
        }

        .fileWrapper {
            flex: 1;
            display: flex;
            flex-wrap: wrap;

            .fileItem {
                width: 133px;
                height: 207px;
                cursor: pointer;

                .neir {
                    padding: 8px;
                    border-radius: 8px;
                    // height: 144px;

                    &:hover {
                        background-color: #f5f5f6;
                    }

                    .imgBox {
                        height: 90px;

                        img {
                            width: 100%;
                            height: 100%;
                        }
                    }

                    .name,
                    .date {
                        display: flex;
                        justify-content: center;
                        font-size: 14px;
                        color: #25262B;
                    }

                    .name {

                        margin: 5px 0;
                    }

                    .date {
                        font-size: 11px;
                        color: #25262b5c;

                    }
                }


            }
        }
    }

    .hidden-input {
        display: none;
    }

    .addWjjDialog {
        color: red;

        ::v-deep {
            .el-dialog__body {
                .imgBox {
                    width: 100%;
                    display: flex;
                    justify-content: center;

                    img {
                        width: 120px;
                        height: 100px;
                    }
                }

            }

            .el-dialog__footer {
                // .cancel {
                //     background: #ffffff;
                //     border: #25262B 1px solid;
                //     color: #333;
                // }
            }
        }
    }
}
</style>